<?php

namespace App\Traits;

use GuzzleHttp\Client as Http;
use Laravel\Passport\Client;
use Laravel\Passport\Passport;

trait AuthTrait
{
    /**
     * 根据授权客户端获取访问令牌    
     * 
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $client_name 客户端名称
     * @param bool $flag 是否返回授权码，默认false
     * @return array
     */    
    public function oauthPassport($username, $password, $client_name, $flag = false)
    {
        $res = [];

        // 根据名称获取客户端证书
        $client = Client::where([
            ['password_client', 3],
            ['name', $client_name]
        ])->firstOrFail();

        // 获取令牌作用域
        $scope = Passport::scopes()->first(function ($item, $key) use ($client_name) {
            return $item->description === $client_name;
        });

        if ($scope) {
            $res = [
                'grant_type' => 'password',
                'client_id' => $client->id,
                'client_secret' => $client->secret,
                'scope' => $scope->id,
                'username' => $username,
                'password' => $password,
            ];

            // 是否返回 access_token
            if ($flag) {
                $http = new Http;
                $response = $http->post(env('APP_URL') . 'oauth/token', [
                    'form_params' => $res,
                ]);
                return json_decode((string) $response->getBody(), true);
            }
        }

        return $res;
    }
}